import {getUserTempId} from '@/utils/userAbout.js'
import {reqGetCode, reqUserAddressList, reqUserInfo, reqUserLogin, reqUserLogout, reqUserRegister} from "@/api";

const state = {
    //初始化的时候 用户的临时标识就存储到state里
    userTempId: getUserTempId(),
    code: '',
  //  token: '', //刷新的时候 state中的数据会清0,这时候用户已经登录过了  就要自动登录了 需要从localStorage中获取到
    token:localStorage.getItem('TOKEN_KEY'),
    userInfo: {},
   userAddressList:[]
}
const mutations = {
    RECEIVE_CODE(state, code) {
        state.code = code
    },
    RECEIVE_TOKEN(state, token) {
        state.token = token
    },
    //token校验过程中获取用户信息
    RECEIVE_USERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    RESET_TOKEN(state) {
        state.token = ""
        state.userInfo={}
    },
    //用户地址信息
    RECEIVE_USERADDRESSLIST(state,userAddressList){
        state.userAddressList=userAddressList
    }
}
const actions = {
    //因为有后续操作,需要return
    async getCode({commit}, phone) {
        const result = await reqGetCode(phone)
        if (result.code === 200) {
            commit('RECEIVE_CODE', result.data)
            return result.data
        } else {
            return Promise.reject('failed')
        }
    }, //注册
    async userRegister({commit}, userInfo) {
        const result = await reqUserRegister(userInfo)
        if (result.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('failed'))
        }
    }, //登录
    async userLogin({commit}, userInfo) {
        const result = await reqUserLogin(userInfo)
        if (result.code === 200) {
            commit('RECEIVE_TOKEN', result.data.token)
            localStorage.setItem('TOKEN_KEY',result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('failed'))
        }
    }, //获取用户信息 因为有后续的操作 所以需要return
    async getUserInfo({commit}) {
        let result = await reqUserInfo()
        if (result.code === 200) {
            commit('RECEIVE_USERINFO', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('failed'))
        }
    }, //清空token
    async resetToken({commit}) {
        commit('RESET_TOKEN')//清空state中的token
        localStorage.removeItem('TOKEN_KEY')//清空localStorage中的token
    },
    //退出登录
    async userLogout({commit,dispatch}){
        let result=await reqUserLogout()
        if (result.code===200){
           dispatch('resetToken')//在store中可以dispatch另外一个的
            return 'ok'
        }else {
            return  Promise.reject(new Error('failed'))
        }
    },
    //用户地址信息
    async getUserAddressList({commit}){
        const result=await reqUserAddressList()
        if (result.code===200){
            commit('RECEIVE_USERADDRESSLIST',result.data)
            return 'ok'
        }else {
            Promise.reject(new Error('failed'))
        }
    }
}

const getters = {}
export default {
    state, mutations, actions, getters
}